let mixinList = require('../../common/mixinList');
Page({
    behaviors: [mixinList],
    data: {
        product_id: '', //接收到的产品id
        info: null, //产品详情信息
        swiper: [], //视频、图片轮播
        current: 0, //当前轮播图片
        detailLoading: true,
        reqUrl: '/api/product/index',
        usePrivateMethod: true,
        evaluateScreenData: [
            { type: '全部', num: 0 },
            { type: '好评', num: 0 },
            { type: '中评', num: 0 },
            { type: '差评', num: 0 },
        ],
        evaluateList: [], //评论列表
        evaluateScreenActive: 0, //评价筛选选中项
        showAddCartPopup: false, //展示加入购物车弹窗
        addCartCurrent: null, //加入购物车商品信息
    },
    onLoad: function (options) {
        const { id, uid } = options;
        if (id) this.data.product_id = id;
        if (uid) {
            //绑定关系
            return this.redirect_login(uid);
        }
        this.getDetail();
    },
    //获取产品详情
    getDetail() {
        this.request(
            {
                url: '/api/product/detail',
                login: false,
                data: { product_id: this.data.product_id },
            },
            res => {
                let swiper = [];
                res.data.photo_list.forEach(item => {
                    swiper.push({
                        url: this.data.imgHost + item.photo + '!img_750',
                        type: 'image',
                    });
                });
                res.data.video &&
                    swiper.unshift({
                        url: this.data.imgHost + res.data.video,
                        type: 'video',
                    });

                [
                    res.data.product_price_int,
                    res.data.product_price_float,
                ] = res.data.product_price.toString().split('.');

                this.setData({ info: res.data, swiper, detailLoading: false });
                this.getList(true);
                this.getEvaluate();
                this.getEvaluateNum();
            },
            () => {
                wx.showModal({
                    content: '商品已下架',
                    confirmColor: '#188075',
                    showCancel: false,
                    success(res) {
                        wx.navigateBack();
                    },
                });
            }
        );
    },
    /**获取在售的商品的请求参数 */
    getParamsData() {
        //页面特殊的请求参数，需要时在页面内覆盖此方法，默认返回{}
        return { supplier_id: this.data.info.supplier.supplier_id };
    },
    /**在售的其他商品请求过滤函数 */
    privateMethod(refresh, res) {
        return new Promise(resolve => {
            const index = res.data.findIndex(item => {
                return item.product_id == this.data.product_id;
            });

            if (index !== -1) {
                res.data.splice(index, 1);
            }

            resolve(res.data);
        });
    },
    /**前往其他在售商品详情页 */
    toOtherDetail({ mark }) {
        wx.navigateTo({
            url: `/pages/good_detail/index?id=${mark.product_id}`,
        });
    },
    //预览商品图片、视频
    previewMedia(e) {
        const { index } = e.mark;
        if (this.data.swiper[index].type === 'video') return;
        wx.previewMedia({
            sources: this.data.swiper,
            current: index,
        });
    },
    /**预览评价图片 */
    priviewEvaluate({ mark }) {
        const { index, photo_index, all } = mark;
        if (photo_index == undefined && !all) return;
        if (all) {
            //查看全部评价
            const { info } = this.data;
            const options = `?product_id=${info.product_id}&product_common_id=${info.product_common_id}&supplier_id=${info.supplier.supplier_id}`;
            return wx.navigateTo({
                url: '/pages/comment/index' + options,
            });
        }
        const sources = this.data.evaluateList[index].photos.map(item => {
            return this.data.imgHost + item;
        });
        wx.previewImage({
            current: sources[photo_index],
            urls: sources,
        });
    },
    /**轮播图切换事件 */
    swiperChange(event) {
        this.setData({
            current: event.detail.current,
        });
    },
    //收藏、取消收藏
    liked() {
        const { info } = this.data;
        this.request(
            {
                url: '/api/user/collect/collect?type=3',
                method: 'POST',
                data: {
                    status: info.collected === 1 ? 0 : 1,
                    can_id: info.product_id,
                },
            },
            () => {
                wx.showToast({
                    title: info.collected === 1 ? '取消成功' : '收藏成功',
                    icon: 'success',
                });
                this.setData({
                    ['info.collected']: info.collected === 1 ? 0 : 1,
                });
                try {
                    const eventChannel = this.getOpenerEventChannel();
                    if (eventChannel) eventChannel.emit('likeOption');
                } catch (error) {}
            },
            () => {
                wx.showToast({
                    title: info.collected === 1 ? '取消失败' : '收藏失败',
                    icon: 'error',
                });
            }
        );
    },
    /**获取产品评价 */
    getEvaluate() {
        const { info, evaluateScreenActive } = this.data;
        this.request(
            {
                url: '/api/comment',
                data: {
                    product_id: info.product_id,
                    product_common_id: info.product_common_id,
                    supplier_id: info.supplier.supplier_id,
                    type: evaluateScreenActive,
                    limit: 3,
                    page: 1,
                },
            },
            res => {
                if (res.data.length > 0)
                    this.setData({ evaluateList: res.data });
                if (evaluateScreenActive === 0)
                    this.setData({
                        ['evaluateScreenData[0].num']: res.count,
                    });
            }
        );
    },
    /**评价筛选条件改变 */
    onScreenChange(e) {
        const { index } = e.currentTarget.dataset;
        if (index === this.data.evaluateScreenActive) return;
        this.setData({ evaluateScreenActive: index, evaluateList: [] });
        this.getEvaluate();
    },
    /**获取评价数量 */
    getEvaluateNum() {
        const { info } = this.data;
        const url = `/api/comment/tongji?product_id=${info.product_id}&product_common_id=${info.product_common_id}&supplier_id=${info.supplier_id}`;
        this.request(
            {
                url,
            },
            ({ data }) => {
                this.setData({
                    ['evaluateScreenData[1].num']: data.praise_count,
                    ['evaluateScreenData[2].num']: data.medium_count,
                    ['evaluateScreenData[3].num']: data.negative_count,
                });
            }
        );
    },
    /**点击加入购物车 */
    openAddcartPopup(e) {
        const { info } = e.currentTarget.dataset;

        if (info.sku === 0)
            return wx.showToast({
                title: '该商品已售空',
                icon: 'none',
            });
        const { imgHost } = this.data;
        const addCartCurrent = {
            product_img: imgHost + info.product_img,
            product_name: info.product_name,
            product_price: info.product_price,
            sku: info.sku,
            unit: info.unit,
            supplier_id: info.supplier.supplier_id,
            supplier_name: info.supplier.title,
            level: info.level,
            norm: info.norm,
            product_id: info.product_id,
            sell_num: info.sell_num,
        };

        this.setData({
            addCartCurrent,
            showAddCartPopup: true,
        });
    },
    //点击分享
    onShareAppMessage() {
        const { info, userInfo, imgHost } = this.data;
        let options = `/pages/good_detail/index?id=${info.product_id}`;
        if (userInfo) options += `&uid=${userInfo.uid}`;
        return {
            title: '向您推荐了' + info.product_name + '，点击即可查看',
            path: options,
            imageUrl: imgHost + info.product_img,
        };
    },
});
